﻿using System;
using ProtoBuf;
using System.IO;
using System.Linq;
using Ayatta.Contract.Domain;
using System.Collections.Generic;

namespace Ayatta.Service.Category
{
    public class CategoryManager
    {
        private readonly IList<ProductCategory> categories;
        private readonly IList<CategoryProp> props;
        private readonly IList<CategoryPropValue> propValues;

        private static readonly Lazy<CategoryManager> LazyInstance =new Lazy<CategoryManager>(() => new CategoryManager());

        public static CategoryManager Instance
        {
            get { return LazyInstance.Value; }
        }

        private CategoryManager()
        {
            var root = "E:/Ayatta/Service/Windows.Service/Ayatta.Service.Cagegory/data/";
            categories = Deserialize<IList<ProductCategory>>(root + "category.bin");
            props = Deserialize<IList<CategoryProp>>(root + "category.prop.bin");
            propValues = Deserialize<IList<CategoryPropValue>>(root + "category.prop.value.bin");
        }

        public IList<ProductCategory> GetCategories(int parentId)
        {
            return categories.Where(o => o.ParentId == parentId).ToList();
        }

        public IList<CategoryProp> GetProps(int categoryId)
        {
            return props.Where(o => o.CategoryId == categoryId).ToList();
        }

        public IList<CategoryPropValue> GetPropValues(int categoryId)
        {
            return propValues.Where(o => o.CategoryId == categoryId).ToList();
        }

        private static void Serialize<T>(T data, string path)
        {
            using (var file = File.Create(path))
            {
                Serializer.Serialize(file, data);
            }
        }

        private static T Deserialize<T>(string path)
        {
            using (var file = File.OpenRead(path))
            {
                return Serializer.Deserialize<T>(file);
            }
        }
    }
}